package com.chatplus.application.processor.channel.img.chatgpt;

import com.chatplus.application.common.logging.SouthernQuietLogger;
import com.chatplus.application.common.logging.SouthernQuietLoggerFactory;
import com.chatplus.application.domain.dto.ChatConfigDto;
import com.chatplus.application.domain.entity.basedata.ApiKeyEntity;
import com.chatplus.application.processor.constant.AiPlatformConstants;
import com.chatplus.application.service.basedata.ApiKeyService;
import com.chatplus.application.service.basedata.ConfigService;
import com.unfbx.chatgpt.OpenAiClient;
import com.unfbx.chatgpt.entity.images.ImageResponse;
import com.unfbx.chatgpt.function.KeyRandomStrategy;
import com.unfbx.chatgpt.interceptor.OpenAILogger;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * ChatGPT 机器人处理器
 *
 * @author chj
 * @date 2023/12/27
 **/
@Service
public class ChatGPTImageProcessor {
    private static final SouthernQuietLogger LOGGER = SouthernQuietLoggerFactory.getLogger(ChatGPTImageProcessor.class);

    private final ConfigService configService;
    private final ApiKeyService apiKeyService;

    public ChatGPTImageProcessor(ConfigService configService, ApiKeyService apiKeyService) {
        this.configService = configService;
        this.apiKeyService = apiKeyService;
    }
    public String process(String prompt, String modelName) {
        ChatConfigDto chatConfigDto = configService.getChatConfig();
        ChatConfigDto.OpenAiBean openAiBean = chatConfigDto.getOpenAi();
        if (openAiBean == null) {
            return null;
        }
        List<ApiKeyEntity> apiKeys = apiKeyService.getApiKeys(AiPlatformConstants.OPEN_AI, "img");
        if (CollectionUtils.isEmpty(apiKeys)) {
            return null;
        }
        List<String> apiKeysList = apiKeys.stream().map(ApiKeyEntity::getValue).collect(Collectors.toList());
        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(new OpenAILogger());
        //!!!!!!测试或者发布到服务器千万不要配置Level == BODY!!!!
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.HEADERS);
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(httpLoggingInterceptor)
                .connectTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(600, TimeUnit.SECONDS)
                .readTimeout(600, TimeUnit.SECONDS).build();
        OpenAiClient openAiClient = OpenAiClient.builder()
                .apiHost(handleHost(openAiBean.getApiUrl()))
                .apiKey(apiKeysList)
                //自定义key使用策略 默认随机策略
                .keyStrategy(new KeyRandomStrategy())
                .okHttpClient(okHttpClient)
                .build();

        ImageResponse imageResponse =  openAiClient.genImages(prompt);
        LOGGER.message("图片生成").context("ImageResponse",imageResponse).info();
        return imageResponse.getData().get(0).getUrl();
    }

    private String handleHost(String url) {
        Pattern pattern = Pattern.compile("(https?://[^/]+/)");
        Matcher matcher = pattern.matcher(url);
        if (matcher.find()) {
            return matcher.group(1);
        }
        return null;
    }
}
